package com.whfc.openapi.api.emp.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.HttpUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.dto.AppJXEmpDTO;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.entity.AppFaceGateRecord;
import com.whfc.emp.param.AppEmpOuterParam;
import com.whfc.emp.param.EmpAttendSyncDataParam;
import com.whfc.emp.service.AppEmpService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 */
@Service
public class OpenApiJxEmpServiceImpl implements OpenApiJxEmpService {

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0")
    private AppEmpService appEmpService;

    @Override
    public void saveOrEdit(String param) {
        JSONObject data = JSONObject.parseObject(param);
        String id = data.getString("id");
        if (!StringUtils.hasText(id)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "缺少员工id");
        }
        // 获取身份证
        String idCard = data.getString("idCard");
        // 基于身份证获取人员信息
        AppEmp appEmp = appEmpService.selectByDeptIdAndIdCardNo(27,idCard);
        if (appEmp == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "未获取到人员");
        }
        // 设置人员编码
        appEmp.setEmpCode(id);
        String photo = data.getString("photo");
        if (photo != null) {
            appEmp.setAvatar(photo);
        }
        String idFrontScan = data.getString("idFrontScan");
        if (idFrontScan != null) {
            appEmp.setIdCardFront(idFrontScan);
        }
        String idReverseScan = data.getString("idReverseScan");
        if (idReverseScan != null) {
            appEmp.setIdCardBack(idReverseScan);
        }
        appEmpService.updateById(appEmp);
    }


    @Override
    public void empExit(String param) {
        JSONObject data = JSONObject.parseObject(param);
        // 获取身份证
        String idCard = data.getString("idCard");
        // 基于身份证获取人员信息
        AppEmp appEmp = appEmpService.selectByDeptIdAndIdCardNo(27,idCard);
        if (appEmp == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "未获取到人员");
        }
        Date datetime = data.getDate("datetime");
        AppEmpOuterParam appEmpOuterParam = new AppEmpOuterParam();
        appEmpOuterParam.setEmpId(appEmp.getId());
        appEmpOuterParam.setDate(datetime == null ?new Date(): datetime);
        appEmpService.outer(appEmpOuterParam);
    }


    @Override
    public void attendanceSave(String param) {
        JSONObject data = JSONObject.parseObject(param);
        EmpAttendSyncDataParam empAttendSyncDataParam = new EmpAttendSyncDataParam();
        empAttendSyncDataParam.setDeptId(27);
        String employeeId = data.getString("employeeId");
        if (employeeId == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "缺少人员参数");
        }
        empAttendSyncDataParam.setPersonGuid(employeeId);
        // 考勤设备id
        String deviceKey = data.getString("id");
        empAttendSyncDataParam.setDeviceKey(deviceKey);

        Date dateTime = data.getDate("datetime");
        empAttendSyncDataParam.setShowTime(dateTime);

        Integer way = data.getInteger("way");
        empAttendSyncDataParam.setDirection(way);
        
        empAttendSyncDataParam.setPicture(data.getString("image"));
        appEmpService.attendanceSave(empAttendSyncDataParam);
    }

    @Override
    public void saveDevice(String param) {

    }

    // 九象实名制测试
    public static void main(String[] args) {
        Long orgId = 1638423405883L;
        String appId = "jx1639362873537";
        String appSecret = "5D7B80E497EC78C32C6D3762A22D056D";
        String version = "v1";
        String method = "labor";
        long timestamp = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orgId",orgId);
        jsonObject.put("pageNum",1);
        jsonObject.put("pageSize",100);
//        String startTime = DateUtil.formatDate(new Date(timestamp - 35*60*1000), "yyyy-MM-dd HH:mm:ss");
//        System.out.println(startTime);
//        String endTime = DateUtil.formatDate(new Date(timestamp), "yyyy-MM-dd HH:mm:ss");
//        jsonObject.put("startDatetime",startTime);
//        jsonObject.put("endDatetime",endTime);
        String jsonString = JSONObject.toJSONString(jsonObject);
        // appSecret+appId=appId&version=version&method=method&timestamp=timestamp&data=data+appSecret

//        String formatSign = String.format("appSecret+appId=%s&version=v1&method=labor&timestamp=%s&data=%s+%s", appId, timestamp, jsonString, appSecret);
//        System.out.println("签名参数拼接======》"+formatSign);
        String sign = encrypt(appSecret + "appId=" + appId + "&version=" + version + "&method=" + method + "&timestamp=" + timestamp + "&data=" + jsonString+appSecret);
        System.out.println("生成的签名======》"+sign);
//        /v1/labor/attendance/record/getDeviceList
        String url  = "http://jiuxiang.9xsmart.com/smart-api/v1/labor/attendance/record/listEnterOutRecordPage?";
//        String url  = "http://jiuxiang.9xsmart.com/smart-api//v1/labor/attendance/record/getDeviceList?";
        String requestUrl = String.format( "appId=%s&version=v1&method=labor&timestamp=%s&sign=%s", appId, timestamp, sign);
        System.out.println("请求地址======》"+url+requestUrl);
        // http://xxxxxx:8080/v1/employee/listAll?appId=appId&version=version&method=method&timestamp=timestamp&sign=sign
        String s = HttpUtil.doPost(url+requestUrl, jsonString);
        JSONObject jsonData = JSONObject.parseObject(s);
        JSONObject data = jsonData.getJSONObject("data");
        List<AppJXEmpDTO> list = data.getJSONArray("list").toJavaList(AppJXEmpDTO.class);
        HashMap<Object, Object> map = new HashMap<>();
        for (AppJXEmpDTO appJXEmpDTO : list) {
            map.put(appJXEmpDTO.getHardwareId(),appJXEmpDTO.getWay());
        }
        System.out.println(map.toString());
    }

    public static String encrypt(String content) {
        try {
            // Create MD5 Hash
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(content.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
                hexString.append(String.format("%02X", 0xFF &
                        messageDigest[i]));
            return hexString.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void workTypeSaveOrEdit(String param) {

    }

    @Override
    public void teamSaveOrEdit(String param) {

    }
}
